package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.pojo.TrafficHomeDetailPageViewBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */

public class DwsApp_3_traffic_page_view_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_3_traffic_page_view_window().init(
                5003,
                3,
                "DwsApp_3_traffic_page_view_window",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 将数据封装为pojo类型
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> thdpvDs = toTrafficHomeDetailPageViewBean(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultDs = windowAndAgg(thdpvDs);
        // 3 将结果写入Clickhouse中
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_TRAFFIC_PAGE_VIEW_WINDOW,TrafficHomeDetailPageViewBean.class));
    }

    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> ds) {
        // 1 创建水印策略
        WatermarkStrategy<TrafficHomeDetailPageViewBean> strategy = WatermarkStrategy.<TrafficHomeDetailPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean t1, TrafficHomeDetailPageViewBean t2) throws Exception {
                        t2.setHomeUvCt(t2.getHomeUvCt() + t1.getHomeUvCt());
                        t2.setGoodDetailUvCt(t2.getGoodDetailUvCt() + t1.getGoodDetailUvCt());
                        return t2;
                    }
                }, new AllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TrafficHomeDetailPageViewBean> values, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        TrafficHomeDetailPageViewBean result = values.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> toTrafficHomeDetailPageViewBean(DataStreamSource<String> ds) {
        return ds.map(JSON::parseObject)
                .keyBy(j -> j.getString("mid"))
                .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {

                    private ValueState<String> goodDetailFlagDate;
                    private ValueState<String> homeFlagDate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        homeFlagDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("homeFlagDate", String.class));
                        goodDetailFlagDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("goodDetailFlagDate", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>.Context ctx, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        Long ts = value.getLong("ts");
                        String currentDate = TimeUtil.parseDateStr(ts, false);
                        String pageId = value.getString("page_id");
                        long homeUvCt = 0L;
                        long goodDetailUvCt = 0L;
                        if ("home".equals(pageId)) {
                            if (!currentDate.equals(homeFlagDate.value())) {
                                homeFlagDate.update(currentDate);
                                homeUvCt = 1L;
                            }
                        }
                        if ("good_detail".equals(pageId)) {
                            if (!currentDate.equals(goodDetailFlagDate.value())) {
                                goodDetailFlagDate.update(currentDate);
                                goodDetailUvCt = 1L;
                            }
                        }
                        if (homeUvCt + goodDetailUvCt == 1){
                            out.collect(
                                    TrafficHomeDetailPageViewBean.builder()
                                            .homeUvCt(homeUvCt)
                                            .goodDetailUvCt(goodDetailUvCt)
                                            .ts(ts)
                                            .build()
                            );
                        }

                    }
                });
    }
}
